#!/usr/bin/env python3

"""
Given a linked list, rotate the list to the right by k places
"""


class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None

    def link(self, node):
        self.next = node
        return node

    def show(self, end='\n'):
        print(f'{self.val}', end=' ')
        if self.next:
            self.next.show(None)
        if end:
            print(end, end='')
            

class Solution:
    def rotateRight(self, head, k):
        length = 0
        current = head
        while current is not None:
            length += 1
            current = current.next
        k = length - k % length
        if k == 0 or k == length:
            return head
        length = 1
        current = head
        while length != k:
            length += 1
            current = current.next
        else:
            new_head = current.next
            tmp_current = current.next
            current.next = None
            current = tmp_current

        while current.next is not None:
            current = current.next
        current.next = head
        return new_head


if __name__ == '__main__':
    head = ListNode(1)
    head.link(ListNode(2))\
        .link(ListNode(3))\
        .link(ListNode(4))\
        .link(ListNode(5))

    head.show()
    s = Solution()
    result = s.rotateRight(head, 2)
    result.show()
    
